package com.rc.saas.tenant.service.member;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rc.saas.tenant.mapper.member.RcMemberGainGradeSettingMapper;
import com.rc.saas.tenant.model.member.RcMemberGainGradeSetting;
import com.rc.saas.tenant.model.member.RcMemberGainGradeSettingExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RcMemberGainGradeSettingServiceImpl implements RcMemberGainGradeSettingService{

    @Autowired
    private RcMemberGainGradeSettingMapper memberGainGradeSettingMapper;

    @Override
    public RcMemberGainGradeSettingMapper getMapper() {
        return memberGainGradeSettingMapper;
    }

    @Override
    public List<RcMemberGainGradeSetting> listMemberGainGradeByGainSetting(Long gainId) {
        RcMemberGainGradeSettingExample example = new RcMemberGainGradeSettingExample();
        example.createCriteria().andMemberGainIdEqualTo(gainId);
        List<RcMemberGainGradeSetting> list = memberGainGradeSettingMapper.selectByExample(example);
        return list;
    }

    @Override
    public void batchInsert(List<RcMemberGainGradeSetting> list) {
        memberGainGradeSettingMapper.batchInsert(list);
    }

    @Override
    public void batchUpdate(List<RcMemberGainGradeSetting> list) {
        list.forEach(gradeSetting -> {
            memberGainGradeSettingMapper.updateByPrimaryKeySelective(gradeSetting);
        });
    }

    @Override
    public void batchDelete(List<RcMemberGainGradeSetting> list) {
        memberGainGradeSettingMapper.batchDelete(list);

    }

    @Override
    public void saveSetting(RcMemberGainGradeSetting setting, TenantUser user) {
        //删除
        memberGainGradeSettingMapper.batchDelete(null);
        //新增
        if (StringUtils.isNotBlank(setting.getTableLstStr())){
            List<RcMemberGainGradeSetting> settings = new ArrayList<>();
            JSONArray jsonArray = JSONArray.parseArray(setting.getTableLstStr());
            for (int i = 0; i <jsonArray.size() ; i++) {
                JSONObject temp = jsonArray.getJSONObject(i);
                RcMemberGainGradeSetting info = new RcMemberGainGradeSetting();
                info.setSettingSort(temp.getInteger("id"));
                info.setRechargeAmount(temp.getBigDecimal("rechargeAmount"));
                info.setGainAmount(temp.getBigDecimal("gainAmount"));
                info.setConsumeUseAmount(temp.getBigDecimal("consumeUseAmount"));
                info.setCreatedBy(user.getLoginName());
                info.setCreatedTime(new Date());
                settings.add(info);
            }
            memberGainGradeSettingMapper.batchInsert(settings);
        }
    }
}
